using UnityEngine;
using System.Collections;
using System.Linq;
using System.Text.RegularExpressions;
using DanielSig.UnityExtensions;
using DanielSig;

[RequireComponent(typeof(CharacterController))]
public class AgentController : MonoBehaviour
{
	public Player ThisPlayer;
	public float Speed;
	public float TurnSpeed;
	
	[Range(0,30)]
	public int OverDrive = 0;
	
	private IAgent _agent;
	private ISensor[] _sensors;
	private GameObject _gameCore;
	
	private static Regex _isolateDigits = new Regex("[^\\d]+");
	
	void Awake()
	{
		_agent = this.GetComponentByInterface<IAgent>();
		_sensors = this.GetComponentsInChildrenByInterface<ISensor>().OrderBy<ISensor, int>(
			x =>
			{
				string number = _isolateDigits.Replace(((Component)x).gameObject.name, "", 99);
				int key = 0;
				int.TryParse(number, out key);
				return key;
			}
		).ToArray();
		_gameCore = GameObject.Find("GameCore");
		GameCore.Register(UpdateAgent);
	}
	void UpdateAgent()
	{
		CharacterController ctrl = (CharacterController)collider;
		for(int i = 0; i < OverDrive + 1; i++)
		{
			Vector3 prev = transform.position;
			
			BroadcastMessage("UpdateSensors");//calls all UpdateSensors() functions found in children
			Move next = _agent.NextMove(_sensors);
			if((next & Move.GoForward) > 0)
				ctrl.SimpleMove(transform.forward * Speed);
			if((next & Move.TurnLeft) > 0)
				transform.Rotate(0F, -TurnSpeed, 0F);
			if((next & Move.TurnRight) > 0)
				transform.Rotate(0F, TurnSpeed, 0F);
			if((next & Move.Shoot) > 0)
				BroadcastMessage("ShootProjectile");
				
			Debug.DrawLine(prev, transform.position, Color.yellow, 0.2F);
		}
	}
	void OnDeath()
	{
		Destroy(gameObject);
		_gameCore.SendMessage("OnPlayerDeath", ThisPlayer);
	}
}